package basic.study.wantOffer.chapter3;

import basic.study.wantOffer.chapter3.Problem18_.ListNode;

/**
 * @author Kevin
 * @date 2020/5/4 11:22
 * 合并有序链表
 */
public class Problem25 {
    /**
     * 递归版本
     */
    public ListNode merge(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        if (list1.val < list2.val) {
            list1.next = merge(list1.next, list2);
            return list1;
        } else {
            list2.next = merge(list1, list2.next);
            return list2;
        }
    }

    /**
     * 非递归
     */
    public ListNode merge2(ListNode list1,ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        ListNode dummyHead = new ListNode(0); // 不能为null
        ListNode p = dummyHead;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                p.next = list1;
                list1 = list1.next;
            } else {
                p.next = list2;
                list2 = list2.next;
            }
            p = p.next;
        }
        p.next = (list1 == null)?list2:list1;
        return dummyHead;
    }
}
